"""
文件名称: views2.py
功能: 将原本的views进行整理，分出光伏相关的部分
创建日期: 2025-01-15
wtb修改于 2025-03-19
"""
from django.http import JsonResponse
from django.views.decorators.csrf import csrf_exempt
from datetime import datetime, timedelta

# 碳效算法嵌入的导入
from index.basic_db_ops import *
from index.basic_db_ops2 import *
from index.models import *

# 导入光伏读写函数
# TODO 如果正常调试的时候需要注释掉
# from index.client_get_or_input_data import input_data
from .JESLS import GreenCellNetwork, AlgorithmConfig
from .db_Session import get_db_session

# 申请修改寄存器充放电数据
# path("virtual_station/Pv_Data_Change/", views2.pv_data_change, name="Pv_Data_Change"),
@csrf_exempt
def pv_data_change(request):
    if request.method == 'POST':
        try:
            # 解析请求体
            data = json.loads(request.body)
            print("pv_data_change函数")
            print("data是", data)
            """
            请求样式
            {
                Charge_discharge:222或238,//控制充放电
                Charge_power:200-400,//
                Discharge_power：200-400,
            }
            """

            charge_discharge = data.get('Charge_discharge')
            charge_power = int(data.get('Charge_power'))
            discharge_power = int(data.get('Discharge_power'))
            for i in range(3):
                message = input_data("input_data",
                                     array_data=[1000, 1000, 1000, charge_discharge, charge_power, discharge_power])
                time.sleep(1)
            # 假设数据处理成功，返回成功响应
            return JsonResponse({'message': 'Data changed successfully'}, status=200)

        except json.JSONDecodeError:
            return JsonResponse({'error': 'Invalid JSON format'}, status=400)
        except Exception as e:
            return JsonResponse({'error': str(e)}, status=500)
    else:
        return JsonResponse({'error': 'Invalid request method'}, status=405)


# 前端获取48小时内光伏、逆变器功率
# path("virtual_station/power_graph/", views2.power_graph, name="power_graph"),
@csrf_exempt
def power_graph(request):
    if request.method == 'POST':
        session = None
        try:
            Session = get_db_session()
            data = json.loads(request.body)
            data_type = data.get('type', 'pv').lower()

            # 使用本地时间计算范围（确保与数据库存储的时区一致）
            now = datetime.now()
            end_time = now.replace(minute=0, second=0, microsecond=0)
            start_time = end_time - timedelta(hours=72)

            print(f"[DEBUG] 本地时间范围：{start_time} ~ {end_time}")

            # 列选择
            column = 'inverter_active_power' if data_type == 'inverter' else 'pv_active_power'
            response_key = 'inverter' if data_type == 'inverter' else 'photovoltaic'

            session = Session()
            sql = text(f"""
                SELECT 
                    -- 关键修复：明确指定时区转换
                    EXTRACT(epoch FROM date_trunc('hour', save_time AT TIME ZONE 'Asia/Shanghai')) * 1000 AS hour_ts,
                    AVG({column}) AS avg_power
                FROM inverter_second_data
                WHERE 
                    save_time >= :start_time AND 
                    save_time < :end_time
                    AND {column} IS NOT NULL
                GROUP BY date_trunc('hour', save_time AT TIME ZONE 'Asia/Shanghai')
                ORDER BY hour_ts;
            """)

            # 打印最终SQL（调试用）
            print("最终SQL:", sql.text.replace('\n', ' '))

            # 执行查询
            result = session.execute(sql, {
                'start_time': start_time,
                'end_time': end_time
            })

            formatted_result = [
                [int(row.hour_ts), float(row.avg_power)]
                for row in result if row.avg_power is not None
            ]

            print(f"[DEBUG] 返回数据样例：{formatted_result[:3]}")
            return JsonResponse({
                response_key: formatted_result
            }, status=200)

        except KeyError:
            return JsonResponse({'error': 'Missing type parameter', 'code': 400}, status=400)
        except Exception as e:
            print(f"[ERROR] 接口异常：{str(e)}")
            return JsonResponse({'error': str(e), 'code': 500}, status=500)
        finally:
            if session:
                session.close()
    else:
        return JsonResponse({'error': '仅支持POST请求', 'code': 405}, status=405)


# from .basic_db_ops import *
# from sqlalchemy import create_engine
# from sqlalchemy.orm import sessionmaker
# import threading
# from index.client_get_or_input_data import get_or_input_data

# 用来测试能否将光伏数据正常写入数据库
# import time
# postgres_user_name = "postgres"
# password = "123456"
# db_name = "system_database"
# engine = create_engine(f'postgresql://{postgres_user_name}:{password}@localhost:5432/{db_name}')
# Session = sessionmaker(bind=engine) # 生成 Session 类
# # 控制循环的开关
# running = True
# try:
#     while running:
#         # 记录本次循环开始时间
#         start_time = time.time()
#         # 调用你的函数
#         write_inverter_second_data1(Session, 1)
#         # 计算剩余等待时间（1秒 - 函数执行时间）
#         elapsed = time.time() - start_time
#         sleep_time = max(0.0, 1.0 - elapsed)  # 避免负数
#         # 精确等待剩余时间
#         time.sleep(sleep_time)
# except KeyboardInterrupt:
#     print("\n循环已手动停止")
#     running = False




@csrf_exempt
def optimize_network(request):
    if request.method == 'POST':
        try:
            Session = get_db_session()
            params = json.loads(request.body)

            # 强制类型验证
            required_params = {
                'num_bs': int,
                'num_users': int,
                'area_size': int
            }

            # 检查参数是否存在且类型正确
            for key, param_type in required_params.items():
                if key not in params:
                    return JsonResponse({'status': 'error', 'message': f'Missing parameter: {key}'}, status=400)
                try:
                    params[key] = param_type(params[key])
                except ValueError:
                    return JsonResponse({'status': 'error', 'message': f'Invalid type for {key}'}, status=400)

            # 创建配置
            config = AlgorithmConfig(
                max_transmit_power=params.get('max_transmit_power', 40),
                system_bandwidth=params.get('bandwidth', 10e6),
                energy_loss_range=tuple(params.get('energy_loss_range', [0.7, 0.9]))
            )

            # 运行算法
            network = GreenCellNetwork(
                num_bs=params['num_bs'],
                num_users=params['num_users'],
                area_size=params['area_size'],
                config=config
            )
            result = network.run()

            # 添加可视化数据
            if result['status'] == 'success':
                result['visualization'] = {
                    'base_stations': [
                        {'x': bs['position'][0], 'y': bs['position'][1],
                         'power': bs['transmit_power']}
                        for bs in result['stations']
                    ],
                    'users': [
                        {'x': user['position'][0], 'y': user['position'][1],
                         'connected': user['connected_bs'] is not None}
                        for user in result['users']
                    ],
                    'connections': [
                        {'from': user['id'], 'to': user['connected_bs']}
                        for user in result['users'] if user['connected_bs'] is not None
                    ]
                }

            return JsonResponse(result)

        except Exception as e:
            return JsonResponse({
                'status': 'error',
                'message': f"Optimization failed: {str(e)}"
            }, status=500)

    return JsonResponse({'status': 'error', 'message': 'Method not allowed'}, status=405)

#
# from django.http import JsonResponse
# from index.tasks import demo_loop
# from celery import current_app
#
#
# def start_demo_loop(request):
#     task = demo_loop.delay()
#     return JsonResponse({'message': '任务已启动', 'task_id': task.id})
#
#
# def stop_demo_loop(request):
#     task_id = request.GET.get('task_id')
#     if task_id:
#         current_app.control.revoke(task_id, terminate=True)
#         return JsonResponse({'message': '任务已停止'})
#     return JsonResponse({'message': '未提供有效的任务 ID'})


# # views.py
# from django.http import HttpResponse
# from django.views import async_view
#
#
# @async_view
# async def my_view(request):
#     return HttpResponse("这是一个异步视图响应")
